﻿package com.sz.common.filter;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.sz.common.ICommonDAO;


public class PolicyFilter implements Filter {

	protected final Log logger = LogFactory.getLog(getClass());
	protected FilterConfig filterConfig = null;
	@SuppressWarnings("unchecked")
	protected List moduleList = null;
	
	@SuppressWarnings("unchecked")
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;

		ServletContext servletContext = this.filterConfig.getServletContext();
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		ICommonDAO dao = (ICommonDAO) context.getBean("CommonDAO");

		try {
			this.moduleList = (List) dao.queryForList("select * from module t where t.policy_flag = 0"); // 取不需要验证权限的module列表
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e.getMessage());
		}
	}
	
	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)	throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		String path = request.getContextPath();  //形如：/otprj
		String uri = request.getRequestURI();//形如：/otprj/ticket.do
		uri = uri.substring(path.length()); //形如: /ticket.do
		
		String flag = uri.substring(uri.lastIndexOf("."));  //形如 .do 或 .ajax
		
		logger.info(String.format("PolicyFilter: %s", uri));
		
		//如果是管理员，则不验证权限
		String usertype = (String)request.getSession().getAttribute("usertype");
		if("1".equals(usertype)) {
			chain.doFilter(servletRequest, servletResponse);
			return;
		}
		
		boolean b = false;		
		//首先看module是不是不需要验证权限
		for(int n = 0; n < this.moduleList.size(); ++n) {
			Map map = (Map)this.moduleList.get(n);
			if(uri.equals(map.get("URL").toString())) {
				b = true;
				break;
			}
		}
		//再判断用户的权限
		if(!b) {
			List list = (List)request.getSession().getAttribute("modules");
			if(list != null) {
				for(int n = 0; n < list.size(); ++n) {
					Map map = (Map)list.get(n);
					if(uri.equals(map.get("URL").toString())) {
						b = true;
						break;
					}
				}
			}
		} 

		if(b) {
			chain.doFilter(servletRequest, servletResponse);
		} else {
			if(flag.equals(".do")) {
			((HttpServletResponse)servletResponse).sendRedirect(path + "/page/nopolicy.jsp");
			} else {
				// .ajax
				((HttpServletResponse)servletResponse).setCharacterEncoding("utf-8");
				((HttpServletResponse)servletResponse).getWriter().print("没有操作权限，请联系系统管理员");
			}
		}
	}

	public void destroy() {
		this.filterConfig = null;
		this.moduleList = null;
	}
}
